<template>
  <div class="cardOcr" v-if="!isShowF && !isShowZ && !isFail">
    <div class="title">请正确拍摄上传身份证正反面</div>
    <div class="tipText">照片要求：拍摄图片完整、清晰、无遮挡</div>
    <div class="takePhotoArea">
      <div class="textArea">
        <div class="areaTitle">身份证人像面</div>
        <div class="AreaText">
          <div>即身份证反面照片</div>
          <div>(包含姓名、公民身份证)</div>
        </div>
      </div>
      <div class="imgArea" @click="chooseImgZ">
        <img src="./img/ID_card.png" alt="" class="img bgImg" />
        <img :src="ocrInfoZ.imgUrlZ" alt="" class="cardImg" />
      </div>
    </div>
    <div class="takePhotoArea">
      <div class="textArea">
        <div class="areaTitle">身份证国徽面</div>
        <div class="AreaText">
          <div>即身份证正面照片</div>
          <div>(包含有效期)</div>
        </div>
      </div>
      <div class="imgArea" @click="chooseImgF">
        <img src="./img/ID_card_fan.png" alt="" class="img bgImg" />
        <img :src="ocrInfoF.imgUrlF" alt="" class="cardImg" />
      </div>
    </div>
    <div class="formTitle">身份证信息</div>
    <div class="formArea">
      <div class="areaItem">
        <div class="itemTitle">姓名</div>
        <div class="itemValue">{{ ocrInfoZ.name }}</div>
      </div>
      <div class="areaItem">
        <div class="itemTitle">身份证号</div>
        <div class="itemValue">{{ ocrInfoZ.id }}</div>
      </div>
      <div class="areaItem">
        <div class="itemTitle">性别</div>
        <div class="itemValue">{{ ocrInfoZ.gender }}</div>
      </div>
      <div class="areaItem">
        <div class="itemTitle">民族</div>
        <div class="itemValue">{{ ocrInfoZ.nationality }}</div>
      </div>
      <div class="adress">
        <div class="itemTitle">地址</div>
        <div class="itemValue">{{ ocrInfoZ.address }}</div>
      </div>
      <div class="areaItem">
        <div class="itemTitle">签发机关</div>
        <div class="itemValue">{{ ocrInfoF.authority }}</div>
      </div>
      <div class="areaItem">
        <div class="itemTitle">有效日期</div>
        <div class="itemValue">{{ ocrInfoF.validDate }}</div>
      </div>
    </div>
    <div class="formTitle">手机验证</div>
    <div class="formArea">
      <up-form
        labelPosition="top"
        labelWidth="300rpx"
        labelStyle="color:#666666;font-size:28rpx;"
        :model="submitInfo"
      >
        <up-form-item label="保证人手机号码" prop="phoneNum">
          <up-input
            v-model="submitInfo.phoneNum"
            placeholder="请输入手机号"
            border="bottom"
            :disabled="isCheck ? true : false"
            customStyle="border-color: #EEEEEE !important; padding:12rpx 0;"
          >
            <template #suffix v-if="!isCheck">
              <div class="getMsgCode" @click="getMsg">获取验证码</div>
            </template>
          </up-input>
        </up-form-item>
        <up-form-item label="验证码" prop="msgCode" v-if="!isCheck">
          <up-input
            v-model="submitInfo.msgCode"
            placeholder="请输入验证码"
            border="bottom"
            customStyle="border-color: #EEEEEE !important; padding:12rpx 0;"
          ></up-input>
        </up-form-item>
        <up-form-item label="邮箱" prop="email">
          <up-input
            v-model="submitInfo.email"
            placeholder="请输入邮箱"
            border="bottom"
            :disabled="isCheck ? true : false"
            customStyle="border-color: #EEEEEE !important; padding:12rpx 0;"
          ></up-input>
        </up-form-item>
        <up-form-item label="送达地址" prop="sendAdress">
          <up-input
            v-model="submitInfo.sendAdress"
            placeholder="请输入送达地址"
            :disabled="isCheck ? true : false"
            border="bottom"
            customStyle="border-color: #EEEEEE !important; padding:12rpx 0;"
          ></up-input>
        </up-form-item>
      </up-form>
      <div class="areaItem">
        <div class="itemTitle">联系人关系</div>
        <div class="itemValue" @click="relationShow = true">
          <div>
            {{ submitInfo.relationState ? submitInfo.relationState : "请选择" }}
          </div>
          <div class="selectIcon"></div>
          <up-picker
            :show="relationShow"
            :columns="relationCols"
            :defaultIndex="[0]"
            @cancel="relationShow = false"
            @confirm="checkRelation"
          ></up-picker>
        </div>
      </div>
    </div>
    <div class="nextStep" @click="nextStep">下一步</div>
  </div>
  <up-modal
    width="500rpx"
    :show="isShowDialog"
    content="小程序需要您允许使用摄像头才能正常采集身份信息"
    confirmText="确定"
    showCancelButton
    cancelText="取消"
    @confirm="openCameraSetting"
    @cancel="isShowDialog = !isShowDialog"
  ></up-modal>
  <div class="camera" v-if="isShowZ">
    <div class="tipsText">请将身份证正面置于此区域</div>
    <div class="cameraArea">
      <camera
        class="camera"
        mode="normal"
        resolution="high"
        device-position="back"
        flash="auto"
      />
    </div>
    <div class="cameraBtn">
      <div class="cancel btn" @click="cancelZ">取消</div>
      <div class="confirm btn" @click="takePhotoZ">下一步</div>
    </div>
  </div>
  <div class="camera" v-if="isShowF">
    <div class="tipsText">请将身份证反面置于此区域</div>
    <div class="cameraArea">
      <camera
        class="camera"
        mode="normal"
        resolution="high"
        device-position="back"
        flash="auto"
      />
    </div>
    <div class="cameraBtn">
      <div class="cancel btn" @click="cancelF">取消</div>
      <div class="confirm btn" @click="takePhotoF">下一步</div>
    </div>
  </div>
  <div class="ocrFail" v-if="isFail">
    <img class="failIcon" src="./img/fail_icon.png" alt="" />
    <div class="failTitle">身份认证失败</div>
    <div class="failTips">身份证扫描失败，请重试哦</div>
    <div class="tryAgain" @click="tryAgain">再试一次</div>
    <div class="goIndex">返回首页</div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import * as http from "../../utils/http";
import { onLoad } from "@dcloudio/uni-app";
import config from "../../utils/config";
let isCheck = ref(false); // 是否查看
let orderId = null;
onLoad((option) => {
  let param = JSON.parse(option.value);
  if (param.isCheck) {
    isCheck.value = true;
    http.perRechPlayersEntityDetail({ id: param.id }).then((res) => {
      submitInfo.phoneNum = res.data.playersPhone;
      submitInfo.email = res.data.playersEmail;
      submitInfo.sendAdress = res.data.playersAddress;
      ocrInfoZ.name = res.data.playersName;
      ocrInfoZ.id = res.data.playersCardNo;
      ocrInfoZ.gender = res.data.sex;
      ocrInfoZ.nationality = res.data.nation;
      ocrInfoZ.address = res.data.address;
      ocrInfoF.validDate = res.data.validDate;
      ocrInfoF.authority = res.data.authority;
      submitInfo.relationState = res.data.playersRelationType;
    });
  } else {
    orderId = param.orderId;
  }
});
const relationShow = ref(false);
const relationCols = reactive([["配偶", "亲属", "朋友", "其他"]]);
const checkRelation = (e) => {
  // #业务代码
  console.log(e.value[0]);
  submitInfo.relationState = e.value[0];
  relationShow.value = false;
};
const submitInfo = reactive({
  phoneNum: "",
  msgCode: "",
  email: "",
  sendAdress: "",
  relationState: "",
});
// 手机验证
const getMsg = () => {
  http.guarantorSendSmsCode({ custPhone: submitInfo.phoneNum }).then((res) => {
    wx.showToast({
      title: "发送短信验证码成功",
      icon: "none",
      duration: 1000,
      mask: true,
    });
  });
};

// 是否授权
const isAuth = ref(false);
// 是否显示弹出框
const isShowDialog = ref(false);
// 进入页面获取授权
onMounted(() => {
  getAuth(); //获取授权
});
// 获取授权
const getAuth = () => {
  wx.getSetting({
    success: (res) => {
      if (!res.authSetting["scope.camera"]) {
        wx.authorize({
          scope: "scope.camera",
          success: () => {
            isAuth.value = true;
          },
          fail: () => {
            isShowDialog.value = true;
          },
        });
      } else {
        isAuth.value = true;
      }
    },
  });
};
// 打开小程序设置
const openCameraSetting = () => {
  wx.getSetting({
    success: (res) => {
      if (res.authSetting && !res.authSetting["scope.camera"]) {
        wx.openSetting({
          success: (res) => {
            if (res.authSetting && res.authSetting["scope.camera"]) {
              isAuth.value = true;
              wx.showToast({
                title: "您已授权使用摄像头",
                icon: "none",
              });
            } else {
              isShowDialog.value = true;
            }
          },
        });
      } else {
      }
    },
  });
};
// 将图片转成base64
const getBase64Data = (path) => {
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().readFile({
      filePath: path,
      encoding: "base64",
      success(res) {
        resolve(res);
      },
      fail(res) {
        reject(res);
      },
    });
  });
};

// 是否显示正面
const isShowZ = ref(false);
// 点击正面弹出相机
const chooseImgZ = () => {
  if (!isCheck.value) {
    wx.showLoading({
      title: "",
      mask: true,
    });
    wx.getSetting({
      success: (res) => {
        wx.hideLoading();
        if (res.authSetting && !res.authSetting["scope.camera"]) {
          isShowDialog.value = true;
        } else {
          isShowZ.value = true;
        }
      },
    });
  }
};
// ocr识别正面信息
const ocrInfoZ = reactive({
  gender: "", //性别
  nationality: "", //民族
  address: "", //住址
  name: "", //姓名
  birth: "", //出生日期
  id: "", //身份证号码
  imgUrlZ: "", //回显正面
  paramZ: "", //上传给后台的正面
  fileName: "", //文件名
});
// 拍照--人像面--正面
const takePhotoZ = () => {
  const ctx = uni.createCameraContext();
  ctx.takePhoto({
    quality: "normal",
    success: (res) => {
      console.log(res);
      isShowZ.value = false;
      wx.showLoading({
        title: "识别中",
        mask: true,
      });
      ocrInfoZ.fileName = res.tempImagePath;
      getBase64Data(res.tempImagePath).then((res) => {
        let base64Data = res.data;
        base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
        // #开始业务代码
        http
          .realNameAuth({
            imageBase64: base64Data,
          })
          .then((res) => {
            if (!res.data.custName) {
              wx.hideLoading();
              wx.showToast({
                title: "请拍摄人像面",
                icon: "none",
                duration: 1500,
                mask: true,
              });
              return;
            }
            if (
              !res.data.custName ||
              !res.data.cardNo ||
              res.data.cardNo.length != 18
            ) {
              wx.hideLoading();
              wx.showToast({
                title: "证件信息扫描失败",
                icon: "none",
                duration: 1500,
                mask: true,
              });
              return;
            } else {
              wx.hideLoading();
              ocrInfoZ.gender = res.data.sex;
              ocrInfoZ.nationality = res.data.nation;
              ocrInfoZ.address = res.data.address;
              ocrInfoZ.name = res.data.custName;
              ocrInfoZ.id = res.data.cardNo;
              ocrInfoZ.birth = res.data.birth;
              ocrInfoZ.imgUrlZ = `data:image/png;base64,${base64Data}`;
              ocrInfoZ.paramZ = base64Data;
            }
          })
          .catch((err) => {
            console.log("识别失败", err);
            wx.hideLoading();
            wx.showToast({
              title: "识别失败",
              icon: "none",
              duration: 1500,
              mask: true,
            });
          });
      });
    },
    fail: (res) => {
      isShowZ.value = false;
      wx.showLoading({
        title: "识别失败",
        mask: true,
      });
      wx.hideLoading();
    },
  });
};
// 取消拍照--人像面--正面
const cancelZ = () => {
  isShowZ.value = false;
};

// 是否回显反面
const isShowF = ref(false);
// 点击反面弹出相机
const chooseImgF = () => {
  if (!isCheck.value) {
    wx.showLoading({
      title: "",
      mask: true,
    });
    wx.getSetting({
      success: (res) => {
        wx.hideLoading();
        if (res.authSetting && !res.authSetting["scope.camera"]) {
          isShowDialog.value = true;
        } else {
          isShowF.value = true;
        }
      },
    });
  }
};
// ocr识别反面信息
const ocrInfoF = reactive({
  startDate: "", //证件启始日
  endDate: "", //证件过期日
  validDate: "", //证件有效期
  authority: "", //签发机关
  imgUrlF: "", //回显反面
  paramF: "", //上传给后台的反面
  fileName: "", //文件名
});
// 拍照--国徽面--反面
const takePhotoF = () => {
  const ctx = uni.createCameraContext();
  ctx.takePhoto({
    quality: "normal",
    success: (res) => {
      isShowF.value = false;
      wx.showLoading({
        title: "识别中",
        mask: true,
      });
      ocrInfoF.fileName = res.tempImagePath;
      getBase64Data(res.tempImagePath).then((res) => {
        let base64Data = res.data;
        base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
        http
          .realNameAuth({ imageBase64: base64Data })
          .then((res) => {
            if (res.data.custName) {
              wx.hideLoading();
              wx.showToast({
                title: "请扫描国徽面",
                icon: "none",
                duration: 1500,
                mask: true,
              });
              return;
            }
            if (!res.data.validDate) {
              wx.hideLoading();
              wx.showToast({
                title: "证件信息扫描失败",
                icon: "none",
                duration: 1000,
                mask: true,
              });
              return;
            } else {
              if (res.data.validDate.length == 17) {
                let day1 =
                  res.data.validDate.substring(9, 13) +
                  "-" +
                  res.data.validDate.substring(13, 15) +
                  "-" +
                  res.data.validDate.substring(15, 17);
                if (day1 == "0000-00-00") {
                  res.data.validDate =
                    res.data.validDate.substring(0, 9) + "长期";
                }
                console.log(day1);
                let day2 = utils.getNowFormatDate();
                console.log(day2);
                if (day1 != "0000-00-00" && new Date(day1) < new Date(day2)) {
                  wx.hideLoading();
                  wx.showToast({
                    title: "证件已过期",
                    icon: "none",
                    duration: 1000,
                    mask: true,
                  });
                  return;
                }
              }
              wx.hideLoading();
              ocrInfoF.startDate = res.data.validDate.split("-")[0];
              ocrInfoF.endDate = res.data.validDate.split("-")[1];
              ocrInfoF.authority = res.data.authority;
              ocrInfoF.validDate = res.data.validDate;
              ocrInfoF.imgUrlF = `data:image/png;base64,${base64Data}`;
              ocrInfoF.paramF = base64Data;
              console.log(ocrInfoF, "ocrInfoF");
            }
          })
          .catch((err) => {
            console.log("识别失败", err);
            wx.hideLoading();
            wx.showToast({
              title: "识别失败",
              icon: "none",
              duration: 1500,
              mask: true,
            });
          });
      });
    },
    fail: (res) => {
      isShowF.value = false;
      wx.showToast({
        title: "识别失败",
        mask: true,
      });
      wx.hideLoading();
    },
  });
};
// 取消拍照--国徽面--反面
const cancelF = () => {
  isShowF.value = false;
};

// 是否显示验证失败
const isFail = ref(false);

// 下一步
const nextStep = () => {
  if (isCheck.value) {
    wx.navigateBack({ delta: 1 });
  } else {
    // 上传文件
    let fileInfoList = [];
    http
      .uploadFile({
        bizType: "B0402",
        fileBase64: ocrInfoZ.paramZ,
        fileName: ocrInfoZ.fileName,
        orderId,
        fileType: ocrInfoZ.fileName.split(".").pop(),
      })
      .then((res) => {
        fileInfoList.push({ bizType: "B0402", fileId: res.data.data.fileId });
        http
          .uploadFile({
            bizType: "B0401",
            fileBase64: ocrInfoF.paramF,
            fileName: ocrInfoF.fileName,
            orderId,
            fileType: ocrInfoF.fileName.split(".").pop(),
          })
          .then((rest) => {
            fileInfoList.push({
              bizType: "B0401",
              fileId: rest.data.data.fileId,
            });
            http
              .perRechPlayersEntityAdd({
                playersType: 2,
                playersRelationType:
                  submitInfo.relationState === "配偶"
                    ? "2"
                    : submitInfo.relationState === "亲属"
                    ? "3"
                    : submitInfo.relationState === "朋友"
                    ? "4"
                    : "5",
                orderId,
                cardName: ocrInfoZ.name,
                CardNo: ocrInfoZ.id,
                sex:
                  ocrInfoZ.gender === "男"
                    ? "0"
                    : ocrInfoZ.gender === "女"
                    ? "1"
                    : "",
                nation: ocrInfoZ.nationality,
                address: ocrInfoZ.address,
                authority: ocrInfoF.authority,
                validDate: ocrInfoF.validDate,
                playersPhone: submitInfo.phoneNum,
                playersEmail: submitInfo.email,
                playersAddress: submitInfo.sendAdress,
                fileInfoList, //文件
              })
              .then((res) => {
                wx.showToast({
                  title: "信息提交成功",
                  icon: "none",
                  duration: 1500,
                  mask: true,
                });
                setTimeout(() => {
                  wx.navigateBack({ delta: 1 });
                }, 1500);
              });
          });
      });
  }
};
</script>
<style>
page {
  background-color: #fff;
}
</style>
<style scoped lang="scss">
.cardOcr {
  .title {
    height: 45rpx;
    line-height: 45rpx;
    color: #333333;
    font-size: 32rpx;
    text-align: center;
    margin-top: 31rpx;
  }

  .tipText {
    height: 33rpx;
    line-height: 33rpx;
    text-align: center;
    color: #333333;
    font-size: 24rpx;
  }

  .takePhotoArea {
    width: 690rpx;
    height: 320rpx;
    margin: 20rpx 30rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 20rpx 0 rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-around;
    align-items: center;

    .textArea {
      width: 35%;
      .areaTitle {
        margin-bottom: 15rpx;
        height: 40rpx;
        line-height: 40rpx;
        font-size: 28rpx;
        text-align: center;
        color: #333333;
      }

      .AreaText {
        font-size: 24rpx;
        text-align: center;
      }
    }

    .imgArea {
      width: 348rpx;
      height: 230rpx;
      position: relative;

      .img {
        width: 100%;
        height: 100%;
      }

      .cardImg {
        width: 230rpx;
        height: 348rpx;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%) rotate(-90deg);
      }

      .bgImg {
        position: absolute;
        z-index: -888;
      }
    }
  }

  .formTitle {
    padding-top: 30rpx;
    padding-left: 52rpx;
    padding-bottom: 10rpx;
    font-size: 28rpx;
    color: #333;
    font-weight: 600;
  }

  .formArea {
    padding: 0 52rpx;
    .areaItem {
      height: 88rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1rpx solid #eeeeee;
      font-size: 28rpx;
      .itemTitle {
        color: #666666;
      }
      .itemValue {
        color: #999999;
      }
    }
    .areaItem {
      padding-left: 5rpx;
      height: 88rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1rpx solid #eeeeee;
      .itemTitle {
        font-size: 28rpx;
        color: #666666;
      }
      .itemValue {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        font-size: 28rpx;
        color: #999;
        .selectIcon {
          width: 12rpx;
          height: 12rpx;
          border-top: 2rpx solid #999999;
          border-right: 2rpx solid #999999;
          transform: rotate(45deg);
          margin-left: 13rpx;
        }
        .selectBankCard {
          width: 100rpx;
          height: 52rpx;
          line-height: 52rpx;
          border-radius: 26rpx;
          text-align: center;
          background-color: #e0eafe;
          font-size: 24rpx;
          color: #406eb0;
        }
        .sendFaceBook {
          width: 110rpx;
          height: 52rpx;
          line-height: 52rpx;
          border-radius: 26rpx;
          text-align: center;
          background-color: #e0eafe;
          font-size: 24rpx;
          color: #406eb0;
          border: 1rpx solid #406eb0;
        }
      }
    }
    .adress {
      height: 132rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      align-items: flex-start;
      border-bottom: 1rpx solid #eeeeee;
      font-size: 28rpx;
    }
    .getMsgCode {
      width: 153rpx;
      height: 52rpx;
      line-height: 52rpx;
      text-align: center;
      border-radius: 26rpx;
      color: #406eb0;
      background-color: #e1eefe;
      font-size: 24rpx;
    }
  }

  .nextStep {
    width: 590rpx;
    height: 88rpx;
    margin: 124rpx 80rpx;
    line-height: 88rpx;
    text-align: center;
    border-radius: 44rpx;
    color: #fff;
    background: #3277f2;
    opacity: 0.5;
    font-size: 34rpx;
  }
}

.camera {
  .cameraArea {
    background-color: #484849;
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    .camera {
      border: 1rpx dashed rgba($color: #000000, $alpha: 0.7);
      height: 832rpx;
      width: 520rpx;
      height: 832rpx;
      width: 520rpx;
    }
  }
  .tipsText {
    width: 360rpx;
    height: 42rpx;
    line-height: 42rpx;
    color: #4d8ced;
    font-size: 30rpx;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%) rotate(90deg);
    left: -100rpx;
  }
  .cameraBtn {
    width: 100%;
    height: 148rpx;
    position: absolute;
    bottom: 115rpx;
    left: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    text-align: center;
    .btn {
      color: #fff;
      transform: rotate(90deg);
    }
    .confirm {
      width: 148rpx;
      height: 68rpx;
      line-height: 68rpx;
      background-color: #4d8ced;
      border-radius: 34rpx;
    }
  }
}

.ocrFail {
  .failIcon {
    width: 203rpx;
    height: 225rpx;
    margin: 43rpx calc(calc(100vw - 203rpx) / 2);
    margin-bottom: 26rpx;
  }
  .failTitle {
    height: 59rpx;
    line-height: 59rpx;
    color: #3c3c3d;
    font-size: 42rpx;
    text-align: center;
    margin-bottom: 24rpx;
  }
  .failTips {
    height: 45rpx;
    line-height: 45rpx;
    color: #333333;
    font-size: 32rpx;
    text-align: center;
  }
  .tryAgain {
    width: 590rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    font-size: 32rpx;
    border-radius: 44rpx;
    background-image: linear-gradient(to right, #619df1, #4478c1);
    color: #fff;
    margin: 186rpx 80rpx 30rpx 80rpx;
  }
  .goIndex {
    width: 590rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    font-size: 32rpx;
    border-radius: 44rpx;
    border: 2rpx solid #b6b6b6;
    margin: 0 80rpx;
  }
}
</style>
